<template>
  <view>
    <s-layout :onShareAppMessage="shareInfo" navbar="goods">
      <!-- 标题栏 -->
      <detailNavbar />

      <!-- 骨架屏 -->
      <detailSkeleton v-if="state.skeletonLoading" />
      <!-- 下架/售罄提醒 -->
      <s-empty v-else-if="state.goodsInfo === null" text="商品不存在或已下架" icon="/static/soldout-empty.png" showAction
        actionText="再逛逛" actionUrl="/pages/goods/list" />
      <block v-else>
        <view class="detail-swiper-selector">
          <!-- 商品轮播图  -->
          <su-swiper class="ss-m-b-14" isPreview :list="state.goodsSwiper" dotStyle="tag" imageMode="widthFix"
            dotCur="bg-mask-40" :seizeHeight="750" />

          <!-- 价格+标题 -->
          <view class="title-card detail-card ss-p-y-40 ss-p-x-20">
            <view class="ss-flex ss-row-between ss-col-center ss-m-b-26">
              <view class="price-box ss-flex ss-col-bottom">
                <view class="price-text ss-m-r-16">
                  {{ state.selectedSkuPrice.price || formatPrice(state.goodsInfo.price) }}
                </view>
                <view class="origin-price-text" v-if="state.goodsInfo.original_price > 0">
                  {{ state.selectedSkuPrice.original_price || state.goodsInfo.original_price }}
                </view>
              </view>
              <view class="sales-text">
                {{ formatSales(state.goodsInfo.sales_show_type, state.goodsInfo.sales) }}
              </view>
            </view>
            <view class="discounts-box ss-flex ss-row-between ss-m-b-28">
              <div class="tag-content">
                <view class="tag-box ss-flex">
                  <view class="tag ss-m-r-10" v-for="promos in state.goodsInfo.promos" :key="promos.id"
                    @tap="onActivity">
                    {{ promos.title }}
                  </view>
                </view>
              </div>

              <!-- <view
                class="get-coupon-box ss-flex ss-col-center ss-m-l-20"
                @tap="state.showModel = true"
                v-if="state.couponInfo.length"
              >
                <view class="discounts-title ss-m-r-8">领券</view>
                <text class="cicon-forward"></text>
              </view> -->
            </view>
            <view class="title-text ss-line-2 ss-m-b-6">{{ state.goodsInfo.title }}</view>
            <view class="subtitle-text ss-line-1">{{ state.goodsInfo.subtitle }}</view>
          </view>
		  <view class="merchant ss-flex ss-col-center">
			  <image :src="sheep.$url.cdn(state.goodsInfo?.store?.thumb||'/static/store/shop-default-avatar.png')" class="avatar"></image>
			  <view class="merchant-name ss-m-r-10">{{state.goodsInfo?.store?.name}}</view>
			  <view class="desc text-c-c">| 官方授权，100%正品</view>
		  </view>
          <!-- 功能卡片 -->
          <view class="detail-cell-card detail-card ss-flex-col">
            <detail-cell-sku v-model="state.selectedSkuPrice.goods_sku_text" :skus="state.goodsInfo.skus"
              @tap="state.showSelectSku = true" />
            <detail-cell-service v-if="state.goodsInfo.service" v-model="state.goodsInfo.service" />
            <detail-cell-params v-if="state.goodsInfo.params" v-model="state.goodsInfo.params" />
          </view>
		  
		 
          <!-- 规格与数量弹框 -->
          <select-sku :goodsInfo="state.goodsInfo" :show="state.showSelectSku" @addCart="onAddCart" @buy="onBuy"
            @change="onSkuChange" @close="state.showSelectSku = false" />
        </view>

        <!-- 评价 -->
        <detail-comment-card class="detail-comment-selector" :goodsId="state.goodsId" />
        <!-- 详情 -->
        <detail-content-card class="detail-content-selector" :content="state.goodsInfo.content" />

        <!-- 活动跳转 -->
        <detail-activity-tip v-if="state.goodsInfo.activities" :data="state.goodsInfo"></detail-activity-tip>

        <!-- 详情tabbar -->
        <detail-tabbar v-model="state.goodsInfo">
          <!-- TODO: 缺货中 已售罄 判断 设计-->

          <view class="buy-box ss-flex ss-col-center ss-p-r-20">
          
            <button v-if="state.goodsInfo.is_in == 0" class="ss-reset-button one-placement" @tap="handleOnePlacement">
              一键铺货
            </button>
            
            <button v-if="state.goodsInfo.is_in == 1" class="ss-reset-button one-placement-end" @tap="state.showSelectSku = true">
              已铺货
            </button>
          </view>
          <!-- <view class="buy-box ss-flex ss-col-center ss-p-r-20"
            v-if="state.goodsInfo.stock <= 0 && state.goodsInfo.is_disabled_buy == 0&&types==''">
            <button class="ss-reset-button disabled-btn" disabled> 已售罄 </button>
          </view> -->
          <view class="buy-box ss-flex ss-col-center ss-p-r-20" v-if="state.goodsInfo.is_disabled_buy == 1">
            <button class="ss-reset-button disabled-btn" disabled> {{ state.goodsInfo.disabled_buy_remark }} </button>
          </view>
        </detail-tabbar>
        <s-coupon-get v-model="state.couponInfo" :show="state.showModel" @close="state.showModel = false"
          @get="onGet" />
        <s-activity-pop v-model="state.activityInfo" :show="state.showActivityModel"
          @close="state.showActivityModel = false" />
      </block>
      <!-- 铺货成功的弹框 -->
      <su-popup :show="show" type="center" round="0" :isMaskClick="true" backgroundColor="transparent" @close="handleCloseModal">
        <view class="distribution-contents">
          <image 
              :src="sheep.$url.cdn('/storage/default/20250419/24e0c5fcac58943520508d742c80cc9b.png')"
              mode="widthFix" 
              class="modal-image" />
          <view class="cont">
            <view class="title">铺货成功</view>
            <view class="content">商品已铺货，您可到铺货记录查看</view>
          </view>
          <view class="btns">
            <view class="btn go-on" @tap="handleCloseModal">继续铺货</view>
            <view class="btn go-record" @tap="goDistributionRecord">去铺货记录</view>
          </view>
        </view>
      </su-popup>
    </s-layout>
  </view>
</template>

<script setup>
import { reactive, ref, computed } from 'vue';
import { onLoad, onPageScroll, onShareTimeline } from '@dcloudio/uni-app';
import sheep from '@/sheep';
import { formatSales, formatGoodsSwiper, formatPrice } from '@/sheep/hooks/useGoods';
import detailNavbar from './components/detail/detail-navbar.vue';
import detailCellSku from './components/detail/detail-cell-sku.vue';
import detailCellService from './components/detail/detail-cell-service.vue';
import detailCellParams from './components/detail/detail-cell-params.vue';
import detailTabbar from './components/detail/detail-tabbar.vue';
import detailSkeleton from './components/detail/detail-skeleton.vue';
import detailCommentCard from './components/detail/detail-comment-card.vue';
import detailContentCard from './components/detail/detail-content-card.vue';
import detailActivityTip from './components/detail/detail-activity-tip.vue';
import selectSku from "./components/s-select-sku/s-select-sku.vue"
import YModal from './components/YModal.vue';
import { isEmpty } from 'lodash';

	const userInfo = computed(() => sheep.$store('user').userInfo);
// import detailActivityTip from './components/detail/detail-activity-tip.vue';
// import detailTab from './components/detail/detail-tab.vue';
// import detailCoupon from './components/detail/detail-coupon.vue';
onPageScroll(() => { });

const state = reactive({
  taskUserId:"",
  goodsId: 0,
  skeletonLoading: true,
  goodsInfo: {
   
  },
  showSelectSku: false,
  goodsSwiper: [],
  selectedSkuPrice: {},
  showModel: false,
  total: 0,
  couponInfo: [],
  showActivityModel: false,
  activityInfo: [],


});

const show = ref(false)

const handleCloseModal = () => {
  show.value = false
}


const handleOnePlacement = async () => {
  const {error,data} = await sheep.$api.distribution.addGoods(userInfo.value.cyq_store_id,state.goodsId)
  if(error == 0){
  	show.value = true
  }else{
		// uni.showToast({
		// 	icon:'none',
		// 	title:msg
		// })
	}
}

const goDistributionRecord = () => {
  sheep.$router.go('/pages/distribution/record')
  handleCloseModal()
}

// 规格变更
function onSkuChange(e) {
  console.log('onSkuChange:', e);
  state.selectedSkuPrice = e;

}

// 添加购物车
function onAddCart(e) {
  sheep.$store('cart').add(e);
}
const shopId=ref(null)
const is_join=ref(0)
const addmyShop=async(obj)=>{
  if(shopId.value==null){
				uni.showModal({
					title: '提示',
					content: '未开通权限，请先入驻商家',
					confirmText: '去申请',
					showCancel:fasle,
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/commission/giveaway/index',
								
							})
						}
					}
				})
			}
			else{
				if(is_join.value==0){
					const data={
					id:obj.id,
					store_ids:shopId.value
				}	
				const {error,data1} = await sheep.$api.store.addStoreGoods(data)
				if(error==0){
					uni.showToast({
						title:'加入成功'
					})
				}
				else{
					uni.showToast({
						title:data1
					})
				}
				}
				else{
					uni.showToast({
						title:'已加入，不能重复加入'
					})

				}
			}
				
}
// 立即购买
function onBuy(e) {
  sheep.$router.go('/pages/order/confirm', {
    data: JSON.stringify({
      order_type: 'goods',
     
      goods_list: [
        {
          goods_id: e.goods_id,
          goods_num: e.goods_num,
          goods_sku_price_id: e.id,
        },
      ],
    }),
    taskUserId:state.taskUserId,
  });
}
//营销活动
function onActivity() {
  state.activityInfo = state.goodsInfo.promos;
  state.showActivityModel = true;
}

//立即领取
async function onGet(id) {
  const { error, msg } = await sheep.$api.coupon.get(id);
  if (error === 0) {
    uni.showToast({
      title: msg,
    });
    setTimeout(() => {
      getCoupon();
    }, 1000);
  }
}

const shareInfo = computed(() => {
  if (isEmpty(state.goodsInfo)) return {};
  return sheep.$platform.share.getShareInfo(
    {
      title: state.goodsInfo.title,
      image: sheep.$url.cdn(state.goodsInfo.image),
      desc: state.goodsInfo.subtitle,
      params: {
        page: '2',
        query: state.goodsInfo.id,
        shopId: shopId.value,
      },
    },
    {
      id: state.goodsInfo.id,
      type: 'goods', // 商品海报
      title: state.goodsInfo.title, // 商品标题
      image: sheep.$url.cdn(state.goodsInfo.image), // 商品主图
      price: state.goodsInfo.price[0], // 商品价格
      original_price: state.goodsInfo.original_price, // 商品原价
    },
  );
});
const types=ref("")
onLoad(async (options) => {
  if(options.shopid){
    shopId.value=options.shopid
  }
  else{
    shopId.value=sheep.$store('user').userInfo.store_id
  }
  if(options.types){
    types.value=options.types
  }
  if(options.is_join){
    is_join.value=options.is_join
  }
  // 非法参数
  if (!options.id) {
    state.goodsInfo = null;
    return;
  }
  if(options.taskUserId){
    state.taskUserId=options.taskUserId
  }
  state.goodsId = options.id;
  
  // 加载商品信息
  sheep.$api.distribution.shopSelectDetails(state.goodsId).then((res) => {
  // sheep.$api.goods.detail(state.goodsId).then((res) => {
    state.skeletonLoading = false;
    if (res.error === 0) {
      state.goodsInfo = res.data;
      state.goodsSwiper = formatGoodsSwiper(state.goodsInfo.images);
    } else {
      // 未找到商品
      state.goodsInfo = null;
    }
  });
  const { error, data } = await sheep.$api.coupon.listByGoods(state.goodsId);
  if (error === 0) {
    state.couponInfo = data;
  }
});

onShareTimeline(() => {
  return {
    title: state.goodsInfo.title,
    path: '/pages/goods/index?id=' + state.goodsInfo.id,
    imageUrl: state.goodsInfo.image,
  };
});
</script>

<style lang="scss" scoped>
@import './style/detail.scss';
</style>
